package android.support.v4.os;

import com.edroid.autorunner.Statics;


/**
 * 
 * @author yichou 2014-8-8
 *
 */
public class ESharedPreferencesImpl extends EHook {
    
    @Override
    public String getClassName() {
        return "android.app.SharedPreferencesImpl";
    }

    @Override
    public void hook() {
        findAndHookMethod("getLong", String.class, long.class, this);
        findAndHookMethod("getInt", String.class, int.class, this);
        findAndHookMethod("getString", String.class, String.class, this);
        
        new EEditorImpl().hook();
    }
    
    private long session_start_time;
    
    @Override
    protected void after(String name, Object[] args, MethodHookParam param) {
        log.i("esp", name + "(" + args[0] + "," + args[1] + ") " + param.getResult());
        
        //12-31 11:33:43.728: I/esp(3072): getLong(session_start_time,0) 1419996815834
        //12-31 11:33:43.728: I/esp(3072): getLong(session_end_time,0) 1419996820386

        if("getLong".equals(name)) {
            if(args[0].equals("session_start_time")) {
            	session_start_time = (Long)param.getResult();
            	
            	param.setResult(session_start_time - Statics.appTime*1000);
            } else if (args[0].equals("session_end_time")) {
            	param.setResult(session_start_time);
			}
        }
        
        super.after(name, args, param);
    }

    public static final class EEditorImpl extends EHook {

        @Override
        public String getClassName() {
            return " android.app.SharedPreferencesImpl$EditorImpl";
        }

        @Override
        public void hook() {
            //Editor putLong(String key, long value)
            findAndHookMethod("putLong", String.class, long.class, this);
            findAndHookMethod("putInt", String.class, int.class, this);
            findAndHookMethod("putString", String.class, String.class, this);
        }
        
        @Override
        protected boolean before(String name, Object[] args, MethodHookParam param) {
            log.i("esp", name + "(" + args[0] + "," + args[1]);
            
            if("putLong".equals(name)) {
                if(args[0].equals("a_end_time") 
                        || "terminate_time".equals(args[0])
                        || "end_millis".equals(args[0])
                        )
                {
//                	log.e("time", name + "(" + args[0] + "," + args[1]);
                	
                    args[1] = (Long)args[1] - 60*1000;
                } else if("duration".equals(args[0])) {
//                	log.e("time", name + "(" + args[0] + "," + args[1]);

                	args[1] = Statics.appTime*1000;
                }
            }
            
            return super.before(name, args, param);
        }
    }
}
